package com.doge.calcalbum.utils

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.doge.calcalbum.BuildConfig
import com.doge.calcalbum.core.BaseDialogFragment
import com.doge.calcalbum.databinding.DialogFragmentEnvBinding
import kotlin.system.exitProcess

private const val key = "data"
private const val folder = "env"
private var testEnv: Boolean? = null
val isTestEnv: Boolean
    get() = testEnv ?: (spReadBoolean(key, false, folder).also { testEnv = it })

fun updateEnv(value: Boolean) = runOnIO {
    testEnv = value
    spWrite(key, value, folder)

    mainHandler.postDelayed({
        exitProcess(0)
    }, 1200)
}

const val debug = "https://inspace.vip/"
const val release = "https://inspace.vip/"
val serviceUrl: String get() = if (isTestEnv) debug else release

object EnvHelper {
    private var counts: Long = 0
    fun switch() {
        if (!BuildConfig.DEBUG) return

        if ((counts++) % 5 == 0L) {
            EnvDialogFragment.newInstance().show(Activities.top?.supportFragmentManager)
        }
    }
}

class EnvDialogFragment : BaseDialogFragment() {
    override val hasShadow: Boolean get() = true
    private var innerBinding: DialogFragmentEnvBinding? = null
    private val binding get() = innerBinding!!


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        innerBinding = innerBinding ?: DialogFragmentEnvBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initialViews()
        binding.vRelease.setTextColor(getColor(if (isTestEnv) "#222222" else "#ff8da5"))
        binding.vTest.setTextColor(getColor(if (isTestEnv) "#ff8da5" else "#222222"))
    }

    private fun initialViews() {
        binding.vRelease.setOnClickCallback {
            updateEnv(false)
            Activities.finishAll()
        }
        binding.vTest.setOnClickCallback {
            updateEnv(true)
            Activities.finishAll()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.vRelease.setOnClickListener(null)
        binding.vTest.setOnClickListener(null)
        innerBinding = null
    }

    companion object {
        fun newInstance(): EnvDialogFragment {
            return EnvDialogFragment()
        }
    }
}
